package pais.robot.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/** HTTP Connector 
 * 
 * Connects to a web server to get HTML text of a URL 
 * 
 */
public class HttpConnection {
  private HttpURLConnection conn_ = null;
  String docUrlBase_ = null; 
  String cgiUrlBase_ = null;
  /* get the HTML document from web server */
  public void connect(String urlString ) throws MalformedURLException, IOException {
    docUrlBase_ = getDocURLBase(urlString);
    cgiUrlBase_ = getCgiURLBase(urlString);
    
    URL url = new URL(urlString);
    conn_ = (HttpURLConnection) url.openConnection();
  }

  public Reader getReader() throws IOException {
    Reader reader = null;

    // try to use the character encoding of HTML stream
    //String encoding = conn_.getContentEncoding();
    String encoding = "EUC_KR";
    if (encoding != null ) {
      try {
        reader = new InputStreamReader(conn_.getInputStream(), encoding);
      } catch (UnsupportedEncodingException e) {
        System.err.println("Error : Unsupported Encoding => " + encoding );
      }
    } else {
      System.err.println("Warning => No content encoding found");
    }

    // if it failed, use system default encoding
    if ( reader == null)
      reader = new InputStreamReader(conn_.getInputStream());


    return new BufferedReader( reader );
  }
  /**
   * Get base path of URL.
   * ex> http://www.foo.com/some_path/doc.html
   *     => http://www.foo.com/some_path
   *     
   * ex> http://www.foo.com
   *     => http://www.foo.com
   *     
   *     @param urlString - The input URL string.
   */
  public static String getDocURLBase(String urlString) {
    String urlBase;

    // Suppose urlString is a form of http://www.foo.com/some_path/doc.html
    int lastSlashIndex = urlString.lastIndexOf('/');
    urlBase = urlString.substring(0, lastSlashIndex + 1  );

    // Check if urlString was a form of http://www.foo.com
    if ( urlBase.endsWith("//")) {
      // Use the urlString as url base
      urlBase = urlString + "/";
    }
    return urlBase;
  }

  /*
   * Get base path of URL that contains cgi,php,jsp scripts
   * 
   * ex> http://www.foo.com/board/view.php?bid=1912
   *     => http://www.foo.com/board/view.php
   *     
   */
  public static String getCgiURLBase(String urlString) {
    String urlBase = null;
    int lastSlashIndex = urlString.lastIndexOf('?');
    if ( lastSlashIndex > 0 ) {
      urlBase = urlString.substring(0, lastSlashIndex   );
    } else { // if '?' is not found in the urlString, the urlString itself is the url of CGI script
      urlBase = urlString;
    }
    return urlBase;
  }

  public InputStream getInputStream() throws IOException {
    return conn_.getInputStream();
  }
  public long docChangeDate() {
    return conn_.getDate();
  }
  public void disconnect() {
    conn_.disconnect();
  }

  /** convert a relative URL to an absolute URL
   * e.g. 1 ] 
   *    /index.html  =>  http://hostIP:port/index.html
   *    
   * e.g. 2 ] 
   *    ?bid=1912  =>  http://hostIP:port/cgi_path_where_the_link_was/cgi_script_where_the_link_was.cgi?bid=1912
   *
   * e.g. 3 ] 
   *    foo/bar.html =>  http://hostIP:port/html_path_where_the_link_was/foo/bar.html
   * @param url  a relative URL 
   */
  public String getAbsoluteURL( String urlString ) {

    urlString = urlString.trim();

    if ( urlString.length() > 0 ) {
      if ( ! urlString.toLowerCase().startsWith("http://") ) {
        String absURLString = null;
        if ( urlString.charAt(0) == '/' ) // e.g. 1
        {
          URL connURL = conn_.getURL();

          // PAIS_BUG:HostIP can change any time by DNS server,but it is permanently stored on HtmlPageTable 
          absURLString = "http://" + connURL.getHost() ;
          if ( connURL.getPort() > 0 ) {
            absURLString += ":" + connURL.getPort();
          }
          absURLString += urlString ;
        } else if ( urlString.charAt(0) == '?') { // e.g. 2
          absURLString = cgiUrlBase_ + urlString;
        } else { // e.g. 3
          absURLString = docUrlBase_ + urlString;
        }	
        return absURLString;
      }
      // PAIS_BUG:Check if URL encoding is not necessary.
      return urlString;
    }
    return "";
  }

}
